package com.ssy.lingxi.member.merchant.handler.validator;

import com.ssy.lingxi.member.merchant.handler.annotation.DateStringLongToLocalDateTimeAnnotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 时间戳格式的字符串转换为LocalDateTime校验注解实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-07-30
 */
public class DateStringLongToLocalDateTimeValidator implements ConstraintValidator<DateStringLongToLocalDateTimeAnnotation, String> {
    private boolean required;
    private boolean nullable;

    @Override
    public void initialize(DateStringLongToLocalDateTimeAnnotation constraintAnnotation) {
        required = constraintAnnotation.required();
        nullable = constraintAnnotation.nullable();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(!required) {
            return true;
        }

        if(value == null || "".equals(value)) {
            return nullable;
        }

        try {
            long timestamp = Long.parseLong(value);
            Instant instant = Instant.ofEpochMilli(timestamp);
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime.ofInstant(instant, zone);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
